

$(document).ready(function() {
	//var tmp = $('#TableContainer').jtable('selectedRows');
	//console.log(tmp);
	//$('#showExtra a').on('click',function() {
		//alert('extra click');
	//});
});


$(document).ready(drawTable);


function drawTable() {
	$('#TableContainer').jtable({
		
		// Options
		title:					'Ofertas',
		paging:					false,
		sorting:				false,
		deleteConfirmation:		true,
		dialogShowEffect:		'fade',	
	    dialogHideEffect:		'fade',
	    selectOnRowClick:		false,
	    selectingCheckboxes:	false,
	    selecting:				false,
	    multiselect:			false,
	    //openChildAsAccordion:	true,
	
		// Actions
		actions: {
	        createAction: 	window.ajaxUrl + '/createOfferAction',
	        listAction: 	window.ajaxUrl + '/readOfferAction',
	        updateAction: 	window.ajaxUrl + '/updateOfferAction',
	        deleteAction: 	window.ajaxUrl + '/deleteOfferAction'
		},
		
		// Fields
		fields: {
			id: {
				key:			true,
				edit:			false,
				create:			false,
				list:			false
			},
			//--- CHILD TABLE DEFINITION FOR "EXTRAS" --------
            Extras: {
                title: 		'',
                width: 		'5%',
                sorting: 	false,
                edit: 		false,
                create: 	false,
                display: 	function (offerData) {
                	var extraData = null;
                    //Create an image that will be used to open child table (for now ... only a link is used)
                    var $img = $('<div id=""><a href="#" title="alterar dados dos extras desta oferta">Extras</a></div>');
                    //Open child table when user clicks the image
                    $img.click(function () {
                        $('#TableContainer').jtable('openChildTable',
                                $img.closest('tr'),
                                {
                        			// Options
                                    title: 		'Extras',
                                    actions: {
                                        createAction: 	window.ajaxUrl + '/createExtraAction',
                                        listAction: 	window.ajaxUrl + '/readExtraAction?offerId=' + offerData.record.id,
                                        updateAction: 	window.ajaxUrl + '/updateExtraAction	',
                                        deleteAction: 	window.ajaxUrl + '/deleteExtraAction'
                                    },
                                    // Fields
                                    fields: {
                                    	name: {
                            				title:			'Nome',
                            				width:			'50%',
                            				type:			'text',
                            				edit:			true,
                            	            create:			true,
                            	            list:			true,
                            	            display:	function(data) {
                            	            	extraData = data;
                            	            }
                            			},
                            			price: {
                            				title:			'Preco',
                            				width:			'10%',
                            				type:			'text',
                            				edit:			false,
                            	            create:			false,
                            	            list:			false
                            			},
                            			active: {
                            				title:			'Activo',
                            				width:			'10%',
                            	            type:			'checkbox',
                            	            values:			{'0':'no','1':'yes'},
                            	            setOnTextClick:	false,
                            	            defaultValue:	'1',
                            				//edit:			true,
                            				//create:		true,
                            				list:			false
                            			},
                            			description: {
                            				title:			'Descrição',
                            				width:			'50%',
                            				type:			'textarea',
                            				list:			true
                            			}
                                    },
                                    
                                    // Events
                                    recordsLoaded: 			function() {
                            			handleChildRowEvents(offerData,extraData);
                            		}
                                }, function (data) { //opened handler
                                    data.childTable.jtable('load');
                                });
                    });
                    //Return image to show on the person row
                    return $img;
                }
            }, //--- END "EXTRA" CHILD TABLE ----------------
			
			name: {
				title:			'Nome',
				width:			'40%',
				type:			'text',
				edit:			true,
	            create:			true,
	            list:			true
			},
			price: {
				title:			'Preco',
				width:			'10%',
				type:			'text',
				edit:			true,
	            create:			true,
	            list:			true
			},
			numberOfClasses: {
				title:			'Aulas',
				width:			'5%',
				type:			'text',
				edit:			true,
	            create:			true,
	            list:			true
			},
			remainingClasses: {
				title:			'Aulas disponiveis',
				width:			'15%',
				type:			'text',
				edit:			false,
	            create:			false,
	            list:			false
			},
			level: {
				title:			'Nivel',
				width:			'10%',
				options:		{'beginner':'beginner','advanced':'advanced'},
				edit:			true,
	            create:			true,
	            list:			true
			},
			minPart: {
				title:			'Minimo de participantes',
				width:			'10%',
				edit:			true,
	            create:			true,
	            list:			true
			},
			maxPart: {
				title:			'Maximo de participantes',
				width:			'10%',
				edit:			true,
	            create:			true,
	            list:			true
			},	
			active: {
				title:			'Activo',
				width:			'10%',
	            type:			'checkbox',
	            values:			{'0':'no','1':'yes'},
	            setOnTextClick:	false,
	            defaultValue:	'1',
				edit:			true,
				create:			true,
				list:			true
			},
			description: {
				title:			'Descrição',
				width:			'15%',
				type:			'textarea',
				list:			false
			}
		},
		
		// Events
		recordsLoaded: 			function() {
			
		}
		
	});
	//call readOfferAction and load data from server into the table
	$('#TableContainer').jtable('load');
}



// handle events from the buttons from the child rows
function handleChildRowEvents(offerData,extraData) {
	
	// remove the event attatched to the element ( 'edit' and 'delete' in child extra table)
	$('.jtable-child-row button').not('.jtable-close-button').unbind('click');
	
	// EDIT
	$('.jtable-child-row .jtable-edit-command-button ').on('click',function(event) {
		console.log('edit');
	});
	
	// DELETE
	$('.jtable-child-row .jtable-delete-command-button ').on('click',function(event) {
		console.log(offerData);
		var properties = {
			width:		300,
			height:		200,
			show: 		'fade',
			hide: 		'fade',
			resize:			function(event,ui) {
			},
			buttons: {
				"Ok": 		function() {
					$.getJSON(window.ajaxUrl + "/tmp",
						{
							offerId:	offerData.record.id,
							extraId:	extraData.record.id
						},
						function(data) {
							//console.log(data);
							console.log($(this));
							// refresh child table
							$('#TableContainer').jtable('reload');
						}
					);
					$(this).dialog("close");
				},
				"Cancelar":	function() {
					$(this).dialog("close");
				}
			}
		};
		$('#deleteExtraConfirmation').dialog(properties);
	});
	
	// NEW
	$('.jtable-child-row .jtable-bottom-panel .jtable-add-record a').on('click',function(event) {
		// remove event from the class .jtable-add-record
		//$(this).parent().unbind('click');
		
		// stop events associated to this anchor
		event.stopPropagation();
		
		// dialog properties
		var properties = {
			width:		200,
			height:		200,
			show: 		'fade',
			hide: 		'fade',
			resize:			function(event,ui) {
			},
			buttons: {
				"Ok": 		function() {
					var extraId = $('select#extraList').val();
					$.getJSON(window.ajaxUrl + "/addExtraOffer",
						{
							offerId:	offerData.record.id,
							extraId:	extraId
						},
						function(data) { //	handle the response from the server to the requeste to add an extra to an offer 
							// refresh child table
						}
					);
					$(this).dialog("close");
				},
				"Cancelar":	function() {
					$(this).dialog("close");
				}
			}
		};
	
		$.getJSON(window.ajaxUrl + "/availableExtras",
			{
				offerId:	offerData.record.id,
				userId:		offerData.record.users_id
			},
			function(data) {
				if (!data) {	// no data returned 
					
				}
				else {			// data returned 
					//console.log(data);
					//console.log(properties.buttons);
					var options = '';
					for ( var i = 0; i < data.length; i++) {
						options += '<option value="' + data[i].id + '">' + data[i].name + '</option>';
					}
					$('select#extraList').html(options);
					$('#createExtraDialog').dialog(properties);
				}
			}
		);
	});
}






function tmp(data) {
	//console.log(data);
	//console.log('tmp');
}
